# coding=utf-8
from socket import *
import threading
import json
from pymongo import MongoClient
from bson.objectid import ObjectId
import time


tcp_server_socket = socket(AF_INET, SOCK_STREAM)

address = ('', 25687)

tcp_server_socket.bind(address)

tcp_server_socket.listen(128)


class myThread (threading.Thread):
    def __init__(self, client):
        threading.Thread.__init__(self)
        self.client = client
        print 'A worker connect'

    def run(self):
        
        data = self.client.recv(1024).decode('utf-8')
        formatting = json.loads(data)

        ids = formatting['id']
        addr = formatting['addr']
        db = formatting['db']
        while True:

            data = self.client.recv(1024)
            if not data:
                print 'a client end'
                break
        
        conn = MongoClient(addr[0], addr[1])
        db = conn[db]['worker']

        a = db.update({'_id': ObjectId(ids)}, {'$set':{'status': 'end', 'end': str(time.strftime("%Y-%m-%d %H:%M %p", time.localtime()))}})
        conn.close()
        self.client.close()



if __name__ == "__main__":
    print 'run heartheat'
    while True:
        client_socket, clientAddr = tcp_server_socket.accept()
        t = myThread(client_socket)
        t.start()
